// components/pagination/index.js
Component({
  properties: {
    currentIndex: {
      type: Number,
      value: 1,
      observer(newVal) {
        this.setData({ index: newVal })
        this.judgeButtonState();
      },
    },
    totalPage: {
      type: Number,
      observer(newVal) {
        this.setData({ total: newVal })
        this.judgeButtonState();
      },
    },
    showPopUp: {
      type: Boolean,
      observer(newVal) {
        this.setData({ showPopUp: newVal })
      },
    },
  },

  data: {
    index: 1,
    total: 10,
    showPopUp: false,
    prevButtonEnable: true,
    nextButtonEnable: true,
  },

  lifetimes: {
    attached: function () {
      this.setData({
        index: this.data.currentIndex,
        total: this.data.totalPage
      })
    },
    detached: function () {
      
    }
  },

  methods: {
    //每次改变页码就调用该函数
    currentChangeEmit: function (touchEnabled) {
      // 自定义组件向父组件传值
      const option = {
        currentIndex: this.data.index,
        touchEnabled: touchEnabled
      };
      // pageChange 自定义名称事件，父组件中使用
      this.triggerEvent('pageChange', option)
      /*
       在父组件中写上bind:pageChange="handleChange",在父组件中就需要调用handleChange事件
      */
    },
    //开启页码弹窗
    shopPagePopup: function () {
      this.setData({ showPopUp: true })
    },
    //关闭页码弹窗
    hidePagePopup: function () {
      this.setData({ showPopUp: false })
    },
    //更改页码点击事件
    changePage: function (e) {
      this.setData({
        showPopUp: false,
        index: e.currentTarget.dataset.index
      })
      this.currentChangeEmit(this.data.prevButtonEnable || this.data.nextButtonEnable);
      this.judgeButtonState();
    },
    //上一页点击事件
    prevPage: function () {
      if (this.data.index <= 1) { 
        return
      }
      this.setData({ index: this.data.index - 1 })
      this.currentChangeEmit(this.data.prevButtonEnable);
      this.judgeButtonState();
    },
    //下一页点击事件
    nextPage: function () {
      if (this.data.index >= this.data.total) {
        return
      }
      this.setData({ index: this.data.index + 1 })
      this.currentChangeEmit(this.data.nextButtonEnable);
      this.judgeButtonState();
    },
    //判断按钮是否为enabled
    judgeButtonState: function () {
      let index = this.data.index;
      this.setData({
        prevButtonEnable: true,
        nextButtonEnable: true
      })
      if (index <= 1){
        this.setData({ prevButtonEnable: false })
      }
      if (index >= this.data.total) {
        this.setData({ nextButtonEnable: false })
      } 
    }
  }
})